package com.nowcoder.community.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @ClassName MailClient
 * @Description
 * @Author hhwu
 * @Date 2022/5/18 15:41
 * Version 1.0
 **/
@Component
public class MailClient {

    private static Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    // 注入发送邮件的核心组件
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    // 将properties中的值注入进来，表示邮件发送方的信息
    private String from;

    public void sendMail(String to, String subject, String content) {// 输入邮件目标，主题，内容
        try {
            MimeMessage message = mailSender.createMimeMessage();// 创建邮件构造器
            MimeMessageHelper helper = new MimeMessageHelper(message);// 使用助手，辅助构建邮件信息
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);// 加上true表示支持发送html邮件，不加的话只能发字符串类型的内容
            mailSender.send(helper.getMimeMessage());// 发送邮件
        } catch (MessagingException e) {
             logger.error("发送邮件失败："+e.getMessage());// 在logback-spring.xml配置文件中设置了日志既打印到控制台，又输出到本地磁盘。
        }

    }
}
